﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;

namespace WPFWebControl
{
    public partial class MainWindow : System.Windows.Window, INotifyPropertyChanged
    {
        public void HideScriptErrors(System.Windows.Controls.WebBrowser wb, bool hide)
        {
            var fiComWebBrowser = typeof(System.Windows.Controls.WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fiComWebBrowser == null) return;
            var objComWebBrowser = fiComWebBrowser.GetValue(wb);
            if (objComWebBrowser == null)
            {
                wb.Loaded += (o, s) => HideScriptErrors(wb, hide); //In case we are to early
                return;
            }
            objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
        }

        private void MyWebBrowser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            if (!m_bCLik && m_bNew)
            {
                m_bNew = false;
                tbLog.Text += "->LoadCompleted";
                Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");

                try
                {
                    //this is very important because we need a reference on Document not null!
                    IServiceProvider serviceProvider = (IServiceProvider)MyWebBrowser.Document;
                    Guid serviceGuid = SID_SWebBrowserApp;
                    Guid iid = typeof(SHDocVw.IWebBrowser2).GUID;
                    SHDocVw.IWebBrowser2 myWebBrowser2 = (SHDocVw.IWebBrowser2)serviceProvider.QueryService(ref serviceGuid, ref iid);


                    SHDocVw.DWebBrowserEvents_Event wbEvents = (SHDocVw.DWebBrowserEvents_Event)myWebBrowser2;
                    //this is the real event handling done
                    wbEvents.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(OnWebBrowserNewWindow);

                }
                catch (Exception exc)
                {

                }               
                StartWaitToClickThread();
            }
            else
            {
                // do nothing
            }
        }

        void OnWebBrowserNewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
        {
            // Set Processed to cancel opening of the new window.

            Processed = true;
        }

    }    
}
